package com.example.demo1.controller;

import com.example.demo1.model.User;
import com.example.demo1.util.CookieUtils;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Key;

@RestController
public class LoginController {
    final String TOKENX = "1234";
    final Key key = MacProvider.generateKey();

    @PostMapping("login")
    public String queryPoolList(@RequestBody User user, HttpServletResponse response, HttpServletRequest request,
                                @CookieValue(value = "token", required = false) String token) {
        if (token == null) {
            System.out.println("key:"+key);
            String compactJws = Jwts.builder()//返回的字符串便是我们的jwt串了
                    .setSubject(user.getUsername())//设置主题
                    .signWith(SignatureAlgorithm.HS256, key)//设置算法（必须）
                    .compact();//这个是全部设置完成后拼成jwt串的方法
            CookieUtils.writeCookie(response, "token", compactJws);
            System.out.println(compactJws);
        } else {
            System.out.println("key:"+key);
            String reqToken = CookieUtils.getCookie(request, "token");
            String username = Jwts.parser().setSigningKey(key).parseClaimsJws(reqToken).getBody().getSubject();
            System.out.println(username);
            if (user.getUsername().equals(username)) {
                return "验证成功!";
            }
        }
        //返回前台
        return "成功";
    }
}
